package com.platform.push.util;

/**
 * @author ：mongo
 * @date ：2021-04-09 18:15:52
 * @description：
 * @modified By：
 * @version: 1.0.0
 */
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtil {
    public static String nowToDateTimeString() {
        return toDateTimeString(new Date());
    }

    public static String nowToDateString() {
        return toString(new Date(), "yyyy-MM-dd");
    }

    public static String dateToMDString(Date date) {
        return toString(date, "MM-dd");
    }


    public static String nowToString(String format) {
        return toString(new Date(), format);
    }

    public static String toString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static String toString(Date date, String format, TimeZone timeZone) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(timeZone);
        return sdf.format(date);
    }

    public static String toLocalDateString(Date date, String format) {
        DateTime isoDate = new DateTime(date).toDateTimeISO();
        return isoDate.toString(format);
    }

    public static String toString_0(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(date);
    }


    public static String toDateTimeString(Date date) {
        return toString(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String toDateTimeString_0(Date date) {
        return toString_0(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String toDateString(Date date) {
        return toString(date, "yyyy-MM-dd");
    }

    public static String toDateString_0(Date date) {
        return toString_0(date, "yyyy-MM-dd");
    }

    public static Date fromString(String strDate, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            return sdf.parse(strDate);
        } catch (Exception e) {
            return null;
        }
    }

    public static Date fromSDateTimeString(String strDate) {
        return fromString(strDate, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date fromString(String strDate, String format, TimeZone timeZone) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(timeZone);
        try {
            return sdf.parse(strDate);
        } catch (Exception e) {
            return null;
        }
    }

    public static Date fromDateTimeString(String strDate) {
        return fromString(strDate, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date getNextDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
        date = calendar.getTime();
        return date;
    }

    /**
     * 返回当前时间前后几天的日期。
     *
     * @param days
     * @return
     */
    public static String getDate(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, days);
        Date date = calendar.getTime();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 传的time时间是否大于给定的几点几分几秒。
     *
     * @param timeSting
     * @return
     */
    public static boolean isTimeBefore(String timeSting, Date time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date givenTime = null;
        String parstString = toDateString_0(time) + " " + timeSting;
        try {
            givenTime = format.parse(parstString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        boolean isBefore = givenTime.before(time);
        return isBefore;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    public static int getAgeByBirth(Date birthDay) throws ParseException {
        if (birthDay == null) {
            return -1;
        }
        int age = 0;
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }


    public static String timestampToString(Timestamp timestamp, String format, TimeZone timeZone) {
        try {
            DateFormat sdf = new SimpleDateFormat(format);
            sdf.setTimeZone(timeZone);
            return sdf.format(timestamp);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String timestampToDateTimeString(Timestamp timestamp, TimeZone timeZone) {
        return timestampToString(timestamp, "yyyy-MM-dd HH:mm", timeZone);
    }

    /**
     * 判断当前日期是星期几<br>
     * <br>
     *
     * @param pTime 修要判断的时间<br>
     * @return dayForWeek 判断结果<br>
     * @Exception 发生异常<br>
     */
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    /**
     * 根据传入的日期，返回星期的第几天
     *
     * @param localDate
     * @return
     */
    public static int dayForWeek(Date localDate) {
        return new DateTime(localDate).getDayOfWeek();
    }

    public static Date getstrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            return format.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    public static Date toUtc(Date localDate) {
        DateTimeZone tz = DateTimeZone.getDefault();
        return new Date(tz.convertLocalToUTC(localDate.getTime(), false));
    }

    public static Date toLocal(Date date) {
        DateTimeZone tz = DateTimeZone.getDefault();
        return new Date(tz.convertUTCToLocal(date.getTime()));
    }

    public static long toLocalInstant(Date date) {
        DateTimeZone tz = DateTimeZone.getDefault();
        return tz.convertUTCToLocal(date.getTime());
    }


    /**
     * 当前时间添加N天
     *
     * @param days
     * @return
     */
    public static Date addDays(int days) {
        return DateTime.now().plusDays(days).toDate();
    }

    public static Date nowAddSeconds(int seconds) {
        return LocalDateTime.now().plusSeconds(seconds).toDate();
    }

    public static Date addSeconds(Date date, int seconds) {
        return LocalDateTime.fromDateFields(date).plusSeconds(seconds).toDate();
    }

    public static Date addMinutes(Date date, int minutes) {
        return LocalDateTime.fromDateFields(date).plusMinutes(minutes).toDate();
    }

    public static Date addMinutes(int minutes) {
        return addMinutes(new Date(), minutes);
    }

    public static Date addHours(Date date, int hours) {
        return LocalDateTime.fromDateFields(date).plusHours(hours).toDate();
    }

    public static Date addMillis(Date date, int millis) {
        return LocalDateTime.fromDateFields(date).plusMillis(millis).toDate();
    }

    /**
     * 当前时间添加N天
     *
     * @param days
     * @return
     */
    public static Date addDays(Date date, int days) {
        return new DateTime(date).plusDays(days).toDate();
    }

    /**
     * 当前时间时分秒转成00:00:00
     *
     * @param localDate
     * @return
     */
    public static Date ignoreTime(Date localDate) {
        DateTime date = new DateTime(localDate);
        return date.plusMillis(-date.getMillisOfDay()).toDate();
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return Long    返回类型
     * @throws
     * @Title: getDateTime
     * @Description: TODO(日期转毫秒数)
     * @author zxf
     */
    public static Long getDateTime(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Long dateTime = 0l;
        try {
            dateTime = format.parse(str).getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dateTime;
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return Date    返回类型
     * @throws
     * @Title: strToUtc
     * @Description: TODO(毫秒转utc时间)
     * @author zxf
     */
    public static Date strToUtc(Long str) {
        str = str - 8 * 60 * 60 * 1000;
        Date nowdate = new Date();
        nowdate.setTime(str);
        DateTime date = new DateTime(nowdate);
        return date.toDateTime(DateTimeZone.UTC).toDate();
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return Date    返回类型
     * @throws
     * @Title: strToDate
     * @Description: TODO(str转Date)
     * @author zxf
     */
    public static Date strToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 将HH:mm时间格式转换成分钟数
     *
     * @param time
     * @return
     */
    public static int getMinutesTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

        try {
            Date start = sdf.parse(time);
            int hours = start.getHours();
            int minutes = start.getMinutes();
            int seconds = start.getSeconds();
            if (hours != 0) {
                int hM = hours * 60;
                if (seconds != 0) {
                    int lastTime = hM + minutes + 1;
                    return lastTime;
                } else {
                    int lastTime = hM + minutes;
                    return lastTime;
                }
            } else {
                if (seconds != 0) {
                    int lastTime = minutes + 1;
                    return lastTime;
                } else {
                    int lastTime = minutes;
                    return lastTime;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public static boolean isToday(Date date) {
        return ignoreTime(date).compareTo(ignoreTime(new Date())) == 0;
    }

//    public static boolean isUtcToday(Date date) {
//        Date a = ignoreTime(toLocal(date));
//        Date b = ignoreTime(toLocal(new Date()));
//        return a.compareTo(b) == 0;
//    }

    public static boolean isUtcTodayV2(Date utcDate) {
        DateTime now = DateTime.now(DateTimeZone.UTC).toDateTime(DateTimeZone.forOffsetHours(8));
        DateTime time = new DateTime(utcDate).toDateTime(DateTimeZone.forOffsetHours(8));
        return now.getDayOfYear() == time.getDayOfYear();
    }

    public static boolean isUtcToday(Date utcDate) {
        DateTime dt = DateTime.now();
        DateTime stime = dt.plusMillis(-dt.getMillisOfDay()).toDateTime(DateTimeZone.UTC);
        DateTime etime = stime.plusDays(1);

        DateTime dateTime = new DateTime(utcDate, DateTimeZone.UTC);
//        return dateTime.getDayOfYear() == .getDayOfYear();
        if (dateTime.compareTo(stime) >= 0 && dateTime.compareTo(etime) < 0)
            return true;
        return false;

    }

    public static Date getTodayDate() {
        DateTime dateTime = new DateTime(toLocal(DateTime.now().toDate()), DateTimeZone.UTC);
        return dateTime.plusMillis(-dateTime.getMillisOfDay()).toDate();
    }

    /**
     * 获取当前月第一天
     * @return
     */
    public static Date getMonthFirstDate() {
        DateTime now = DateTime.now();
        return now.plusDays(-now.getDayOfMonth()).toDate();
    }
}

